import React, { useState, useEffect } from 'react';
import {
  Card,
  Form,
  Input,
  Button,
  Space,
  message,
  Spin,
  Select,
  DatePicker,
  Row,
  Col
} from 'antd';
import {
  ArrowLeftOutlined,
  SaveOutlined,
  UserOutlined
} from '@ant-design/icons';
import { useParams, useNavigate } from 'react-router-dom';
import { useAuth } from '../../contexts/AuthContext';
import apiService from '../../services/apiService';
import moment from 'moment';

const { Option } = Select;
const { TextArea } = Input;

const StudentEdit = () => {
  const { id } = useParams();
  const navigate = useNavigate();
  const { isAdmin } = useAuth();
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [student, setStudent] = useState(null);
  const isEdit = !!id;

  useEffect(() => {
    if (!isAdmin()) {
      message.error('权限不足');
      navigate('/students');
      return;
    }

    if (isEdit) {
      loadStudentDetail();
    }
  }, [id, isAdmin, navigate, isEdit]);

  const loadStudentDetail = async () => {
    try {
      setLoading(true);
      const data = await apiService.getStudentById(id);
      setStudent(data);

      // 填充表单数据
      form.setFieldsValue({
        ...data,
        birthDate: data.birthDate ? moment(data.birthDate) : null
      });
    } catch (error) {
      message.error('加载学生信息失败');
      console.error('加载学生信息失败:', error);
      navigate('/students');
    } finally {
      setLoading(false);
    }
  };

  const handleSubmit = async (values) => {
    try {
      setSubmitting(true);

      const submitData = {
        ...values,
        birthDate: values.birthDate ? values.birthDate.format('YYYY-MM-DD') : null
      };

      if (isEdit) {
        await apiService.updateStudent(id, submitData);
        message.success('学生信息更新成功');
      } else {
        await apiService.createStudent(submitData);
        message.success('学生创建成功');
      }

      navigate('/students');
    } catch (error) {
      const errorMessage = error.response?.data?.message || error.message;
      message.error(isEdit ? `更新学生信息失败：${errorMessage}` : `创建学生失败：${errorMessage}`);
      console.error('提交失败:', error);
    } finally {
      setSubmitting(false);
    }
  };

  const handleCancel = () => {
    navigate('/students');
  };

  if (loading) {
    return (
      <div style={{ textAlign: 'center', padding: '50px' }}>
        <Spin size="large" />
      </div>
    );
  }

  return (
    <div>
      <div style={{ marginBottom: 16 }}>
        <Button
          icon={<ArrowLeftOutlined />}
          onClick={handleCancel}
        >
          返回学生列表
        </Button>
      </div>

      <Card
        title={
          <Space>
            <UserOutlined />
            {isEdit ? '编辑学生' : '新建学生'}
          </Space>
        }
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSubmit}
          initialValues={{
            gender: 'MALE'
          }}
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                label="学号"
                name="studentId"
                rules={[
                  { required: true, message: '请输入学号' },
                  { pattern: /^[A-Za-z0-9]+$/, message: '学号只能包含字母和数字' }
                ]}
              >
                <Input placeholder="请输入学号" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label="姓名"
                name="name"
                rules={[
                  { required: true, message: '请输入姓名' },
                  { min: 2, max: 20, message: '姓名长度应在2-20个字符之间' }
                ]}
              >
                <Input placeholder="请输入姓名" />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                label="性别"
                name="gender"
                rules={[{ required: true, message: '请选择性别' }]}
              >
                <Select placeholder="请选择性别">
                  <Option value="MALE">男</Option>
                  <Option value="FEMALE">女</Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label="出生日期"
                name="birthDate"
              >
                <DatePicker
                  style={{ width: '100%' }}
                  placeholder="请选择出生日期"
                  format="YYYY-MM-DD"
                />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                label="邮箱"
                name="email"
                rules={[
                  { required: true, message: '请输入邮箱' },
                  { type: 'email', message: '请输入有效的邮箱地址' }
                ]}
              >
                <Input placeholder="请输入邮箱" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label="电话"
                name="phone"
                rules={[
                  { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号码' }
                ]}
              >
                <Input placeholder="请输入电话号码" />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                label="专业"
                name="major"
                rules={[
                  { required: true, message: '请输入专业' },
                  { max: 50, message: '专业名称不能超过50个字符' }
                ]}
              >
                <Input placeholder="请输入专业" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label="班级"
                name="className"
                rules={[
                  { required: true, message: '请输入班级' },
                  { max: 30, message: '班级名称不能超过30个字符' }
                ]}
              >
                <Input placeholder="请输入班级" />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                label="入学年份"
                name="enrollmentYear"
                rules={[
                  { required: true, message: '请输入入学年份' },
                  { pattern: /^\d{4}$/, message: '请输入有效的年份' }
                ]}
              >
                <Input placeholder="请输入入学年份" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label="地址"
                name="address"
                rules={[
                  { max: 200, message: '地址不能超过200个字符' }
                ]}
              >
                <Input placeholder="请输入地址" />
              </Form.Item>
            </Col>
          </Row>

          {!isEdit && (
            <Row gutter={16}>
              <Col span={12}>
                <Form.Item
                  label="账号"
                  name="username"
                  rules={[
                    { required: true, message: '账号' },
                    { min: 5, message: '账号至少5位' }
                  ]}
                >
                  <Input placeholder="请输入账号" />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  label="密码"
                  name="password"
                  rules={[
                    { required: true, message: '请输入密码' },
                    { min: 6, message: '密码至少6位' }
                  ]}
                >
                  <Input.Password placeholder="请输入密码" />
                </Form.Item>
              </Col>
            </Row>
          )}

          <Form.Item>
            <Space>
              <Button
                type="primary"
                htmlType="submit"
                icon={<SaveOutlined />}
                loading={submitting}
              >
                {isEdit ? '更新' : '创建'}
              </Button>
              <Button onClick={handleCancel}>
                取消
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
    </div>
  );
};

export default StudentEdit;